package com.xing.util;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.xing.util.bean.Task;
import com.xing.util.bean.WeakTask;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class ThreadUtil {

    private static class Holder {
        private static final ThreadUtil instance = new ThreadUtil();
    }

    public static ThreadUtil getInstance() {
        return Holder.instance;
    }

    Handler mHandler;
    ScheduledExecutorService mExecutorService;

    private ThreadUtil() {
        mExecutorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
        mHandler = new Handler(Looper.getMainLooper());
    }

    public void runOnMainThread(Runnable runnable) {
        mHandler.post(runnable);
    }

    /**
     * 该方法会阻塞线程
     */
    public <V> V runOnChildThread(Callable<V> callable) {
        try {
            return mExecutorService.submit(callable).get();
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void runOnChildThread(Runnable runnable) {
        mExecutorService.execute(runnable);
    }

    public <V> void execWork2Main(Callable<V> callable, Task<V> task) {


    }


    public void shutdown() {
        mExecutorService.shutdown();
        mHandler.removeCallbacksAndMessages(null);
    }

    public boolean isRunMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }

}
